import { createContext, useContext, useMemo, useState } from 'react'
import { NavLink } from 'react-router-dom'
import { Route, Redirect, useLocation, useHistory } from 'react-router-dom'
import { Switch } from 'react-router-dom'

const api = {
  login() {
    return fetch('https://randomuser.me/api')
      .then((resp) => resp.json())
      .then((json) => json.results[0].login)
  },
  logout() {
    return new Promise((resolve) => setTimeout(resolve, 100))
  },
}

const UserContext = createContext()
const UserContextProvider = ({ children }) => {
  const [user, setUser] = useState(null)
  const contextValue = useMemo(() => ({ user, setUser }), [user])

  return <UserContext.Provider value={contextValue}>{children}</UserContext.Provider>
}
const useUserContext = () => useContext(UserContext)

const Public = () => <h2>公共页面</h2>
const Login = () => {
  const { setUser } = useUserContext()
  const location = useLocation()
  const history = useHistory()
  console.log('location:', location, 'history:', history)
  return (
    <>
      <h2>登录</h2>
      <button
        onClick={() => {
          api.login().then((user) => {
            setUser(user)
            history.push(location?.state?.from || '/auth/pub')
          })
        }}
      >
        登录
      </button>
    </>
  )
}
const MyPage = () => {
  const { user, setUser } = useUserContext()
  const history = useHistory()
  return (
    <>
      <h2>我的页面</h2>
      <p>你好，{user && user.username}</p>
      <button
        onClick={() => {
          api.logout().then(() => {
            setUser(null)
            history.push('/auth/login')
          })
        }}
      >
        登出
      </button>
    </>
  )
}

const MyPage2 = () => <h2>我的第二个私密页面</h2>

const MyRoute = (props) => {
  const { user } = useUserContext()
  const location = useLocation()
  return user ? <Route {...props} /> : <Redirect to={{ pathname: '/auth/login', state: { from: location } }} />
}

const AuthDemo = () => {
  const tabInfos = [
    {
      to: '/pub',
      text: '公开页面',
    },
    {
      to: '/login',
      text: '登录',
    },
    {
      to: '/my',
      text: '我的',
    },
    {
      to: '/my2',
      text: '我的私密',
    },
  ]
  return (
    <UserContextProvider>
      <h1>自动智能路由</h1>
      {tabInfos.map((item, index) => (
        <span key={index}>
          <NavLink
            to={'/auth' + item.to}
            style={(isActive) => ({
              textDecoration: isActive ? 'none' : 'underline',
            })}
          >
            {item.text}
          </NavLink>
          {'  '}
        </span>
      ))}
      <Switch>
        <Route path="/auth/pub" component={Public} />
        <Route path="/auth/login" component={Login} />
        <MyRoute path="/auth/my" component={MyPage} />
        <MyRoute path="/auth/my2" component={MyPage2} />
      </Switch>
    </UserContextProvider>
  )
}

export default AuthDemo
